import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Alert,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Divider,
  Chip,
  Grid,
} from '@mui/material';
import { Iconify } from 'src/components/iconify';
import { DashboardContent } from 'src/layouts/dashboard';
import { getOrGenerateDeviceId, getDeviceInfoForDebug } from 'src/utils/deviceId';
import { safeApiCall, getAuthHeader, handleTokenExpired, extractDeviceIdFromToken } from 'src/utils/api';

interface DeviceInfo {
  deviceId: string;
  loginTime: number;
  lastActive: number;
  userAgent?: string;
  loginIp?: string;
}

export function UserDeviceManagement() {
  const [devices, setDevices] = useState<DeviceInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');
  const [severity, setSeverity] = useState<'success' | 'error' | 'info' | 'warning'>('info');
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const [showLogoutDeviceDialog, setShowLogoutDeviceDialog] = useState(false);
  const [selectedDeviceId, setSelectedDeviceId] = useState<string>('');
  const [selectedDeviceInfo, setSelectedDeviceInfo] = useState<DeviceInfo | null>(null);
  const [currentDeviceId, setCurrentDeviceId] = useState<string>('');

  // 获取当前设备ID
  useEffect(() => {
    // 优先从token中提取设备ID，如果没有则使用本地生成的
    const tokenDeviceId = extractDeviceIdFromToken();
    if (tokenDeviceId) {
      setCurrentDeviceId(tokenDeviceId);
      console.log('Using deviceId from token:', tokenDeviceId);
    } else {
      const localDeviceId = getOrGenerateDeviceId();
      setCurrentDeviceId(localDeviceId);
      console.log('Using local deviceId:', localDeviceId);
    }
  }, []);

  // 获取用户设备信息
  const fetchDeviceInfo = async () => {
    try {
      setLoading(true);
      
      // 检查token是否存在
      const token = localStorage.getItem('token');
      console.log('Current token:', token ? `${token.substring(0, 30)}...` : 'null');
      
      if (!token) {
        setMessage('未找到登录token，请重新登录');
        setSeverity('error');
        setTimeout(() => {
          window.location.href = '/sign-in';
        }, 2000);
        return;
      }
      
      // 获取设备数量
      const countResult = await safeApiCall('/api/user/device/count', 'GET', null, getAuthHeader());
      
      console.log('Count API result:', countResult); // 调试信息
      
      if (countResult.success) {
        const countData = countResult.data;
        setMessage(`当前活跃设备数量: ${countData.data.activeDeviceCount}`);
        setSeverity('info');
      } else if (countResult.error === 'token过期') {
        console.log('Token expired detected in count API'); // 调试信息
        // Token过期，跳转到登录页面
        handleTokenExpired(setMessage, setSeverity);
        return;
      } else {
        setMessage(countResult.error || '获取设备数量失败');
        setSeverity('error');
      }
      
      // 获取设备列表
      const listResult = await safeApiCall('/api/user/device/list', 'GET', null, getAuthHeader());
      
      console.log('List API result:', listResult); // 调试信息
      
      if (listResult.success) {
        const listData = listResult.data;
        setDevices(listData.data || []);
      } else if (listResult.error === 'token过期') {
        console.log('Token expired detected in list API'); // 调试信息
        // Token过期，跳转到登录页面
        handleTokenExpired(setMessage, setSeverity);
        return;
      } else {
        setMessage(listResult.error || '获取设备列表失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error fetching device info:', error);
      setMessage('获取设备信息失败');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };

  // 强制下线所有设备
  const handleForceLogout = async () => {
    try {
      setLoading(true);
      const result = await safeApiCall('/api/user/device/force-logout', 'POST', null, getAuthHeader());
      
      if (result.success) {
        setMessage('强制下线成功，请重新登录');
        setSeverity('success');
        // 清除本地存储并跳转到登录页
        setTimeout(() => {
          localStorage.clear();
          window.location.href = '/sign-in';
        }, 2000);
      } else if (result.error === 'token过期') {
        // Token过期，跳转到登录页面
        handleTokenExpired(setMessage, setSeverity);
        return;
      } else {
        setMessage(result.error || '强制下线失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error forcing logout:', error);
      setMessage('强制下线失败');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };

  // 下线特定设备
  const handleLogoutDevice = async (deviceId: string) => {
    try {
      setLoading(true);
      const result = await safeApiCall(`/api/user/device/logout-device?deviceId=${encodeURIComponent(deviceId)}`, 'POST', null, getAuthHeader());
      
      if (result.success) {
        setMessage('设备下线成功');
        setSeverity('success');
        // 刷新设备列表
        setTimeout(() => {
          fetchDeviceInfo();
        }, 1000);
      } else if (result.error === 'token过期') {
        // Token过期，跳转到登录页面
        handleTokenExpired(setMessage, setSeverity);
        return;
      } else {
        setMessage(result.error || '设备下线失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error logging out device:', error);
      setMessage('设备下线失败');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };

  // 显示下线设备确认弹窗
  const showLogoutDeviceConfirm = (device: DeviceInfo) => {
    setSelectedDeviceInfo(device);
    setShowLogoutDeviceDialog(true);
  };

  // 确认下线设备
  const confirmLogoutDevice = async () => {
    if (selectedDeviceInfo) {
      await handleLogoutDevice(selectedDeviceInfo.deviceId);
      setShowLogoutDeviceDialog(false);
      setSelectedDeviceInfo(null);
    }
  };

  useEffect(() => {
    fetchDeviceInfo();
  }, []);

  // 格式化时间
  const formatTime = (timestamp: number) => {
    if (!timestamp) return '未知';
    return new Date(timestamp).toLocaleString('zh-CN');
  };

  // 获取设备类型
  const getDeviceType = (userAgent: string) => {
    if (!userAgent) return '未知';
    if (userAgent.includes('Mobile')) return '移动设备';
    if (userAgent.includes('Tablet')) return '平板设备';
    return '桌面设备';
  };

  return (
    <DashboardContent maxWidth="xl">
      <Box>
        <Typography variant="h4" sx={{ mb: 3 }}>
          设备管理
        </Typography>

        {message && (
          <Alert severity={severity} sx={{ mb: 2 }} onClose={() => setMessage('')}>
            {message}
          </Alert>
        )}

        {/* 当前设备信息 */}
        <Card sx={{ mb: 3 }}>
          <CardContent>
            <Box display="flex" alignItems="center" gap={2} sx={{ mb: 2 }}>
              <Typography variant="h6">
                当前设备
              </Typography>
              <Chip 
                label="正在使用" 
                color="success" 
                size="small"
                icon={<Iconify icon="eva:radio-button-on-fill" />}
                sx={{ fontWeight: 'bold' }}
              />
            </Box>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 2, fontStyle: 'italic' }}>
              💻 这是您当前正在使用的设备，所有操作都将在此设备上执行
            </Typography>
            <Grid container spacing={2}>
              <Grid item xs={12} md={6}>
                <Typography variant="body2" color="text.secondary">
                  设备ID: <Chip label={currentDeviceId} size="small" />
                </Typography>
              </Grid>
              <Grid item xs={12} md={6}>
                <Typography variant="body2" color="text.secondary">
                  设备类型: {getDeviceType(navigator.userAgent)}
                </Typography>
              </Grid>
              <Grid item xs={12} md={6}>
                <Typography variant="body2" color="text.secondary">
                  屏幕分辨率: {screen.width} × {screen.height}
                </Typography>
              </Grid>
              <Grid item xs={12} md={6}>
                <Typography variant="body2" color="text.secondary">
                  平台: {navigator.platform}
                </Typography>
              </Grid>
            </Grid>
            <Button
              variant="outlined"
              color="primary"
              onClick={fetchDeviceInfo}
              disabled={loading}
              sx={{ mt: 2 }}
            >
              刷新设备信息
            </Button>
          </CardContent>
        </Card>

        {/* 安全操作 */}
        <Card sx={{ mb: 3 }}>
          <CardContent>
            <Typography variant="h6" sx={{ mb: 2 }}>
              安全操作
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
              强制下线所有设备将清除所有登录会话，包括当前设备
            </Typography>
            <Button
              variant="contained"
              color="error"
              onClick={() => setShowConfirmDialog(true)}
              disabled={loading}
            >
              强制下线所有设备
            </Button>
          </CardContent>
        </Card>

        {/* 设备列表 */}
        <Card>
          <CardContent>
            <Typography variant="h6" sx={{ mb: 2 }}>
              登录设备列表
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
              显示您当前登录的所有设备
            </Typography>
            <Alert severity="info" sx={{ mb: 2 }}>
              <Box sx={{ fontSize: '0.875rem' }}>
                💡 <strong>当前设备</strong>：带有蓝色边框和"当前设备"标签的设备是您正在使用的设备
              </Box>
              <Box sx={{ mt: 1, fontSize: '0.875rem' }}>
                🔒 <strong>其他设备</strong>：您可以下线其他设备以保护账户安全
              </Box>
            </Alert>
            {devices.length === 0 ? (
              <Typography variant="body2" color="text.secondary">
                暂无设备信息
              </Typography>
            ) : (
              <Box>
                <List>
                  {devices.map((device, index) => {
                    const isCurrentDevice = device.deviceId === currentDeviceId;
                    return (
                      <React.Fragment key={device.deviceId}>
                        <ListItem
                          sx={{
                            backgroundColor: isCurrentDevice ? 'rgba(25, 118, 210, 0.08)' : 'transparent',
                            border: isCurrentDevice ? '2px solid #1976d2' : '1px solid #e0e0e0',
                            borderRadius: isCurrentDevice ? '8px' : '4px',
                            marginBottom: 1,
                          }}
                        >
                          <ListItemText
                            primary={
                              <Box display="flex" alignItems="center" gap={1}>
                                <Typography 
                                  variant="subtitle1" 
                                  sx={{ 
                                    fontWeight: isCurrentDevice ? 'bold' : 'normal',
                                    color: isCurrentDevice ? '#1976d2' : 'inherit'
                                  }}
                                >
                                  {isCurrentDevice ? '当前设备' : '其他设备'}
                                </Typography>
                                {isCurrentDevice && (
                                  <Chip 
                                    label="当前设备" 
                                    color="primary" 
                                    size="small" 
                                    sx={{ fontWeight: 'bold' }}
                                  />
                                )}
                              </Box>
                            }
                            secondary={
                              <Box>
                                <Box sx={{ mb: 0.5, fontSize: '0.875rem', color: 'text.secondary' }}>
                                  <strong>设备ID:</strong> {device.deviceId}
                                </Box>
                                <Box sx={{ mb: 0.5, fontSize: '0.875rem', color: 'text.secondary' }}>
                                  <strong>登录时间:</strong> {formatTime(device.loginTime)}
                                </Box>
                                {device.userAgent && (
                                  <Box sx={{ mb: 0.5, fontSize: '0.875rem', color: 'text.secondary' }}>
                                    <strong>设备类型:</strong> {getDeviceType(device.userAgent)}
                                  </Box>
                                )}
                                {device.loginIp && (
                                  <Box sx={{ mb: 0.5, fontSize: '0.875rem', color: 'text.secondary' }}>
                                    <strong>登录IP:</strong> {device.loginIp}
                                  </Box>
                                )}
                                {isCurrentDevice && (
                                  <Box 
                                    sx={{ 
                                      fontWeight: 'bold',
                                      fontStyle: 'italic',
                                      mt: 1,
                                      p: 1,
                                      fontSize: '0.875rem',
                                      color: 'primary.main',
                                      backgroundColor: 'rgba(25, 118, 210, 0.1)',
                                      borderRadius: '4px',
                                      border: '1px solid rgba(25, 118, 210, 0.3)'
                                    }}
                                  >
                                    🎯 这是您当前使用的设备
                                  </Box>
                                )}
                              </Box>
                            }
                          />
                          <ListItemSecondaryAction>
                            {!isCurrentDevice && (
                              <IconButton
                                edge="end"
                                onClick={() => showLogoutDeviceConfirm(device)}
                                disabled={loading}
                                color="error"
                                title="下线此设备"
                              >
                                <Iconify icon="eva:trash-2-outline" />
                              </IconButton>
                            )}
                            {isCurrentDevice && (
                              <Chip 
                                label="当前使用中" 
                                color="success" 
                                size="small"
                                icon={<Iconify icon="eva:radio-button-on-fill" />}
                                sx={{ mr: 1 }}
                              />
                            )}
                          </ListItemSecondaryAction>
                        </ListItem>
                        {index < devices.length - 1 && <Divider />}
                      </React.Fragment>
                    );
                  })}
                </List>
              </Box>
            )}
          </CardContent>
        </Card>

        {/* 确认对话框 */}
        <Dialog open={showConfirmDialog} onClose={() => setShowConfirmDialog(false)}>
          <DialogTitle>确认操作</DialogTitle>
          <DialogContent>
            <Typography>
              确定要强制下线所有设备吗？此操作将清除所有登录会话，您需要重新登录。
            </Typography>
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setShowConfirmDialog(false)}>取消</Button>
            <Button onClick={handleForceLogout} color="error" variant="contained">
              确认
            </Button>
          </DialogActions>
        </Dialog>

        {/* 下线设备确认对话框 */}
        <Dialog
          open={showLogoutDeviceDialog}
          onClose={() => setShowLogoutDeviceDialog(false)}
          aria-labelledby="logout-device-dialog-title"
          aria-describedby="logout-device-dialog-description"
          maxWidth="sm"
          fullWidth
        >
          <DialogTitle id="logout-device-dialog-title">
            <Box display="flex" alignItems="center" gap={1}>
              <Iconify icon="eva:alert-triangle-fill" color="warning.main" />
              确认下线设备
            </Box>
          </DialogTitle>
          <DialogContent>
            <Typography variant="body1" sx={{ mb: 2 }}>
              确定要下线以下设备吗？此操作将清除该设备的登录会话。
            </Typography>
            
            {selectedDeviceInfo && (
              <Card variant="outlined" sx={{ p: 2, mb: 2 }}>
                <Typography variant="subtitle2" color="error" sx={{ mb: 1 }}>
                  ⚠️ 即将下线的设备信息：
                </Typography>
                <Box sx={{ pl: 2 }}>
                  <Typography variant="body2" sx={{ mb: 0.5 }}>
                    <strong>设备ID:</strong> {selectedDeviceInfo.deviceId}
                  </Typography>
                  <Typography variant="body2" sx={{ mb: 0.5 }}>
                    <strong>登录时间:</strong> {formatTime(selectedDeviceInfo.loginTime)}
                  </Typography>
                  {selectedDeviceInfo.userAgent && (
                    <Typography variant="body2" sx={{ mb: 0.5 }}>
                      <strong>设备类型:</strong> {getDeviceType(selectedDeviceInfo.userAgent)}
                    </Typography>
                  )}
                  {selectedDeviceInfo.loginIp && (
                    <Typography variant="body2" sx={{ mb: 0.5 }}>
                      <strong>登录IP:</strong> {selectedDeviceInfo.loginIp}
                    </Typography>
                  )}
                </Box>
              </Card>
            )}
            
            <Alert severity="warning" sx={{ mt: 2 }}>
              <Box sx={{ fontSize: '0.875rem' }}>
                💡 <strong>注意：</strong>下线后，该设备上的用户需要重新登录才能访问系统。
              </Box>
            </Alert>
          </DialogContent>
          <DialogActions>
            <Button 
              onClick={() => setShowLogoutDeviceDialog(false)}
              variant="outlined"
            >
              取消
            </Button>
            <Button 
              onClick={confirmLogoutDevice} 
              color="error" 
              variant="contained"
              disabled={loading}
              startIcon={<Iconify icon="eva:trash-2-outline" />}
            >
              确认下线
            </Button>
          </DialogActions>
        </Dialog>
      </Box>
    </DashboardContent>
  );
}
